<?php
$ro=file_get_contents('php://input'); //得到前端的json文件
$user=json_decode($ro,true);   //转变成php数组
$userId=$user['userId'];   //取出对应数据
$bookId=$user['bookId'];
$newDate=$user['newDate'];  
$PDate=$user['PDate'];


//连接数据库
$link=new mysqli('127.0.0.1','root','root','books_manage_system','3306');
if($link->connect_error){
    die('连接失败'.$link->connect_error);
}else{
    //连接成功，设置编码格式
    mysqli_set_charset($link,'utf8');
    $link->query('SET NAMES UTF8');

    //存储数据
    $result=array();

    $sql1="select * from books where id='$bookId'";
    $sql3="select * from users where id='$userId'";
    $re1=$link->query($sql1);
    $re3=$link->query($sql3);
    $row1=mysqli_fetch_assoc($re1);
    $row3=mysqli_fetch_assoc($re3);
    $borrowBookIdO=$row3['borrowBookId'];
    //添加借阅书籍id
    $borrowBookId=$row3['borrowBookId'].','.$bookId;
    if($row1['status']=='1'){
        //已借阅状态进行书籍归还
        $sql8="update books set lenduserid=NULL,status='0',returnDate='$newDate',borrowDate=NULL where id='$bookId'";
        //以‘,’将字符串分割成数组
        $d=explode(",",$borrowBookIdO);
        array_splice($d,array_search($bookId,$d),1);
        //以‘,’分割数组成字符串
        $id=implode(',',$d);
        $sql9="update users set borrowBookId='$id' where id='$userId'";
        $re8=$link->query($sql8);
        $re9=$link->query($sql9);
        if($re8>0 && $re9>0){
         $result['status']='success';
         $result['message']='还书成功';
        }
    }else{
        //未借阅状态进行书籍借阅  进行身份绑定
        $sql5="update books set lenduserid='$userId',status='1',borrowDate='$newDate',planDate='$PDate',returnDate=NULL where id='$bookId'";
        $sql4="update users set borrowBookId='$borrowBookId' where id='$userId'";
        $re5=$link->query($sql5);
        $re4=$link->query($sql4);
         //返回信息
         if ($re5>0 && $re4>0) {
           $result['status']='success';
           $result['message']='借阅成功';
         }else{
            $sql6="update books set lenduserid=NULL,status='0' where id='$bookId'";
            $sql7="update users set borrowBookId='$borrowBookIdO' where id='$userId'";
            $result['status']='fail';
            $result['message']='借阅失败';
         }
    }
mysqli_free_result($re1); //释放结果集
mysqli_free_result($re3); //释放结果集
//关闭数据库
$link->close();
die(json_encode($result));
}